package com.vote.web;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.vote.dto.TopicDto;
import com.vote.dto.VoteDto;
import com.vote.entity.Vote;
import com.vote.service.ITopicService;
import com.vote.service.IVoteService;
import com.vote.vo.ResultEntity;
import com.vote.vo.TopicVo;
import com.vote.vo.VoVo;
import com.vote.vo.VoteVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author vote group
 * @since 2020-04-08
 */
@RestController
@RequestMapping("/vote")
@Slf4j
public class VoteController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ITopicService iTopicService;

    /**
     * 查询投票信息列表
     *
     * @param voteDto
     * @return
     */
    @RequestMapping("/list")
    public ResultEntity voteList(VoteDto voteDto) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        Map<String, Integer> entries = hashOperations.entries(voteDto.getTid() + "");
        Set<Map.Entry<String, Integer>> entries1 = entries.entrySet();
        List<VoteVo> votes = new ArrayList<>();
        for (Map.Entry<String, Integer> stringStringEntry : entries1) {
            VoteVo voteVo = new VoteVo();
            voteVo.setTid(voteDto.getTid());
            voteVo.setOpt(stringStringEntry.getKey());
            voteVo.setNum(stringStringEntry.getValue());
            votes.add(voteVo);
        }
        return ResultEntity.ok("查询成功", votes);
    }

    @RequestMapping("/vote")
    public ResultEntity vote(VoteDto voteDto) {
        if(null!=voteDto.getTid()&&voteDto.getTid()!=0&&null!=voteDto.getOpt()&&!"".equals(voteDto.getOpt())){
            redisTemplate.opsForHash().increment(String.valueOf(voteDto.getTid()), voteDto.getOpt(), 1);
            return ResultEntity.ok("投票成功");
        }
        return ResultEntity.ok("当前人数过多请稍后重试");
    }

    @RequestMapping("/getLists")
    public ResultEntity getLists(VoteDto voteDto) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        Integer topicdefault = (Integer)redisTemplate.opsForValue().get("topicdefault");
        if (null!= topicdefault&&topicdefault!=0) {
            voteDto.setTid(topicdefault);
        }else{
            List<TopicVo> topics = iTopicService.getTopics(null);
            voteDto.setTid(topics.get(0).getTid());
        }

        VoVo vovo = new VoVo();
        vovo.setOpts(hashOperations.keys(voteDto.getTid() + "").toArray());
        vovo.setNums(hashOperations.values(voteDto.getTid() + "").toArray());
        return ResultEntity.ok(vovo);
    }



}
